package com.qtu.product_service.controller;

import com.qtu.product_service.service.ElasticSearchService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ElasticSearch搜索
 */
@Slf4j
@Controller
@RequestMapping("api/elastic")
public class ElasticSearchController {

    @Autowired
    private ElasticSearchService elasticSearchService;

    @ApiOperation("从数据库中导入商品到ElasticSearch库")
    @RequestMapping("save")
    public void save(){
        try {
            boolean b = elasticSearchService.saveAll();
        } catch (Exception e) {
            log.error("从数据库中导入商品到ElasticSearch库，异常："+e);
        }
    }


    @ApiOperation("商品搜索")
    @ResponseBody
    @GetMapping("search")
    public List<Map<String, Object>> search(String token,String key){
        try {
            List<Map<String, Object>> search = elasticSearchService.search(key);
            for (Map<String, Object> stringObjectMap : search) {
                for (Map.Entry<String, Object> e : stringObjectMap.entrySet()) {
                    System.out.println(e.getKey()+"    "+e.getValue());
                }
            }
            return search;
        } catch (Exception e) {
            log.error("商品搜索，异常："+e);
        }
        return null;
    }
}
